package milu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sleepycat.dbxml.XmlDocument;
import com.sleepycat.dbxml.XmlException;
import com.sleepycat.dbxml.XmlQueryContext;
import com.sleepycat.dbxml.XmlResults;
import com.sleepycat.dbxml.XmlTransaction;
import com.sleepycat.dbxml.XmlValue;

import milu.dbxml.DbXmlContext;
import milu.dbxml.Preparable;

/**
 * Servlet implementation class BcQuery
 */
public class BcQuery extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final SimpleDateFormat ISODateFormatter =
			new SimpleDateFormat("yyyy-MM-dd");

	@Override
	protected void doGet(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		String date = req.getParameter("d");
		String chid = req.getParameter("c");
		if (null == date)
			date = ISODateFormatter.format(new Date());
		if (null == chid)
			chid = "ard";
		DbXmlContext dbxml = (DbXmlContext)
				getServletContext().getAttribute("dbxml");
		Preparable pq = dbxml.getPreparedQuery("bc-by-date-and-channel");
		XmlResults res = null;
		XmlTransaction txn = null;
		try {
			XmlQueryContext xqc = dbxml.getQueryContext();
			XmlResults values = dbxml.getManager().createResults();
			values.add(new XmlValue(XmlValue.DATE, "2010-02-20"));
			values.add(new XmlValue(XmlValue.DATE, "2010-02-21"));
			xqc.setVariableValue("date", values);
			xqc.setVariableValue("chid", new XmlValue(chid));
			txn = dbxml.makeTransaction();
			res = pq.execute(txn, xqc);
			out.format("Suche nach chid = %s und date = %s%n", chid, date);
			out.println("Dokumente gefunden:");
			int count = 0;
			while (res.hasNext()) {
				count++;
				XmlValue val = res.next();
				XmlDocument doc = val.asDocument();
				out.println(doc.getName());
				doc.delete();
				val.delete();
			}
			res.delete();
			txn.commit();
			out.format("insgesamt %d Dokumente gefunden%n", count);
		} catch (XmlException e) {
			try {
				if (res != null)
					res.delete();
				if (null != txn)
					txn.abort();
			} catch (XmlException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
}
